package com.liangxy.news.ui.auth;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.liangxy.news.R;
import com.liangxy.news.database.AppDatabase;
import com.liangxy.news.model.User;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Forgot password activity for password reset
 */
public class ForgotPasswordActivity extends AppCompatActivity {
    
    private EditText etPhoneNumber;
    private EditText etVerificationCode;
    private EditText etNewPassword;
    private EditText etConfirmPassword;
    private Button btnResetPassword;
    private Button btnGetVerificationCode;
    private ProgressBar progressBar;
    
    private ExecutorService executorService;
    private CountDownTimer countDownTimer;
    private String generatedVerificationCode;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgot_password);
        
        // Initialize components
        etPhoneNumber = findViewById(R.id.etPhoneNumber);
        etVerificationCode = findViewById(R.id.etVerificationCode);
        etNewPassword = findViewById(R.id.etNewPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);
        btnResetPassword = findViewById(R.id.btnResetPassword);
        btnGetVerificationCode = findViewById(R.id.btnGetVerificationCode);
        progressBar = findViewById(R.id.progressBar);
        
        executorService = Executors.newSingleThreadExecutor();
        
        // Set click listeners
        btnResetPassword.setOnClickListener(v -> resetPassword());
        btnGetVerificationCode.setOnClickListener(v -> getVerificationCode());
    }
    
    /**
     * Generate and send verification code
     */
    private void getVerificationCode() {
        String phoneNumber = etPhoneNumber.getText().toString().trim();
        
        // Validate phone number
        if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() != 11) {
            etPhoneNumber.setError("请输入正确的手机号");
            return;
        }
        
        // Check if user exists
        executorService.execute(() -> {
            AppDatabase database = AppDatabase.getInstance(getApplicationContext());
            User existingUser = database.userDao().getUserByPhoneNumber(phoneNumber);
            
            runOnUiThread(() -> {
                if (existingUser == null) {
                    etPhoneNumber.setError("该手机号未注册");
                } else {
                    // Generate a random 6-digit verification code
                    Random random = new Random();
                    generatedVerificationCode = String.format("%06d", random.nextInt(1000000));
                    
                    // In a real app, this would be sent via SMS
                    // For this demo, just show it in a toast
                    Toast.makeText(ForgotPasswordActivity.this, "验证码: " + generatedVerificationCode, Toast.LENGTH_LONG).show();
                    
                    // Start countdown timer
                    startCountDownTimer();
                }
            });
        });
    }
    
    /**
     * Start countdown timer for verification code button
     */
    private void startCountDownTimer() {
        btnGetVerificationCode.setEnabled(false);
        
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                btnGetVerificationCode.setText(millisUntilFinished / 1000 + "秒后重新获取");
            }
            
            @Override
            public void onFinish() {
                btnGetVerificationCode.setText(R.string.get_verification_code);
                btnGetVerificationCode.setEnabled(true);
            }
        }.start();
    }
    
    /**
     * Reset password with provided information
     */
    private void resetPassword() {
        String phoneNumber = etPhoneNumber.getText().toString().trim();
        String verificationCode = etVerificationCode.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        
        // Validate input
        if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() != 11) {
            etPhoneNumber.setError("请输入正确的手机号");
            return;
        }
        
        if (TextUtils.isEmpty(verificationCode)) {
            etVerificationCode.setError("请输入验证码");
            return;
        }
        
        if (!verificationCode.equals(generatedVerificationCode)) {
            etVerificationCode.setError("验证码错误");
            return;
        }
        
        if (TextUtils.isEmpty(newPassword)) {
            etNewPassword.setError("请输入新密码");
            return;
        }
        
        if (newPassword.length() < 6) {
            etNewPassword.setError("密码长度不能少于6位");
            return;
        }
        
        if (TextUtils.isEmpty(confirmPassword)) {
            etConfirmPassword.setError("请确认密码");
            return;
        }
        
        if (!newPassword.equals(confirmPassword)) {
            etConfirmPassword.setError("两次输入的密码不一致");
            return;
        }
        
        // Show progress
        progressBar.setVisibility(View.VISIBLE);
        
        // Update password in database
        executorService.execute(() -> {
            AppDatabase database = AppDatabase.getInstance(getApplicationContext());
            User user = database.userDao().getUserByPhoneNumber(phoneNumber);
            
            if (user == null) {
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    etPhoneNumber.setError("该手机号未注册");
                });
                return;
            }
            
            // Update password
            database.userDao().updateUserPassword(phoneNumber, newPassword);
            
            runOnUiThread(() -> {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(ForgotPasswordActivity.this, R.string.reset_password_success, Toast.LENGTH_SHORT).show();
                finish();
            });
        });
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (executorService != null) {
            executorService.shutdown();
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
} 